import store from '@/store'
import { watch } from 'vue'
import { THEME_DARK, THEME_LIGHT, THEME_SYSTEM } from '@/constants'

/**
 * 监听系统主题变更
 */
let matchMedia
const watchSystemThemeChange = () => {
  if (matchMedia) return
  matchMedia = window.matchMedia('(prefers-color-scheme: dark)')
  // 监听主题变更
  matchMedia.onchange = function () {
    changeTheme(THEME_SYSTEM)
  }
}

/**
 * 变更主题
 */
const changeTheme = (val) => {
  let themeClassName = ''
  if (val === THEME_DARK) {
    themeClassName = 'dark'
  } else if (val === THEME_LIGHT) {
    themeClassName = 'light'
  } else if (val === THEME_SYSTEM) {
    watchSystemThemeChange()
    themeClassName = matchMedia.matches ? 'dark' : 'light'
  }
  document.querySelector('html')?.setAttribute('class', themeClassName)
}

export default () => {
  watch(() => store.getters.themeType, changeTheme, {
    immediate: true
  })
}
